#!/bin/bash

# Enrigin GStreamer 插件安装脚本

set -e

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=========================================="
echo "  Enrigin GStreamer 插件安装"
echo "=========================================="
echo ""

# 检查是否为 root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}错误: 请使用 sudo 运行此脚本${NC}"
    exit 1
fi

# 检测架构
ARCH=$(uname -m)
if [ "$ARCH" == "aarch64" ]; then
    GST_PLUGIN_DIR="/usr/lib/aarch64-linux-gnu/gstreamer-1.0"
elif [ "$ARCH" == "x86_64" ]; then
    GST_PLUGIN_DIR="/usr/lib/x86_64-linux-gnu/gstreamer-1.0"
else
    echo -e "${RED}错误: 不支持的架构 $ARCH${NC}"
    exit 1
fi

echo "检测到架构: $ARCH"
echo "插件安装目录: $GST_PLUGIN_DIR"
echo ""

# 检查构建目录
if [ ! -d "build" ]; then
    echo -e "${RED}错误: build 目录不存在，请先运行 ./scripts/build_all.sh${NC}"
    exit 1
fi

cd build

# 检查插件文件
if [ ! -f "libgstenrigindec.so" ]; then
    echo -e "${RED}错误: libgstenrigindec.so 不存在${NC}"
    exit 1
fi

if [ ! -f "libgstenriginenc.so" ]; then
    echo -e "${RED}错误: libgstenriginenc.so 不存在${NC}"
    exit 1
fi

# 创建插件目录（如果不存在）
mkdir -p "$GST_PLUGIN_DIR"

# 安装插件
echo "安装插件..."
cp -v libgstenrigindec.so "$GST_PLUGIN_DIR/"
cp -v libgstenriginenc.so "$GST_PLUGIN_DIR/"

# 设置权限
chmod 644 "$GST_PLUGIN_DIR/libgstenrigindec.so"
chmod 644 "$GST_PLUGIN_DIR/libgstenriginenc.so"

echo ""
echo -e "${GREEN}✓ 插件安装成功${NC}"
echo ""

# 验证安装
echo "验证安装..."
echo ""

if gst-inspect-1.0 enrigindec > /dev/null 2>&1; then
    echo -e "${GREEN}✓ enrigindec 插件已加载${NC}"
else
    echo -e "${RED}✗ enrigindec 插件加载失败${NC}"
    exit 1
fi

if gst-inspect-1.0 enriginenc > /dev/null 2>&1; then
    echo -e "${GREEN}✓ enriginenc 插件已加载${NC}"
else
    echo -e "${RED}✗ enriginenc 插件加载失败${NC}"
    exit 1
fi

echo ""
echo "=========================================="
echo "  安装完成"
echo "=========================================="
echo ""
echo "插件位置:"
echo "  $GST_PLUGIN_DIR/libgstenrigindec.so"
echo "  $GST_PLUGIN_DIR/libgstenriginenc.so"
echo ""
echo "验证命令:"
echo "  gst-inspect-1.0 enrigindec"
echo "  gst-inspect-1.0 enriginenc"
echo ""
echo "快速测试:"
echo "  cd tests"
echo "  ./test_enrigindec.sh"
echo "  ./test_enriginenc.sh"
echo ""
